package com.fangcang.ebk.order.controller;

import com.fangcang.common.PaginationSupportDTO;
import com.fangcang.common.ResponseDTO;
import com.fangcang.common.enums.ErrorCodeEnum;
import com.fangcang.common.enums.ResultCodeEnum;
import com.fangcang.common.util.StringUtil;
import com.fangcang.common.util.excel.ExcelUtils;
import com.fangcang.ebk.common.controller.BaseController;
import com.fangcang.ebk.request.LockRequestDTO;
import com.fangcang.ebk.request.QueryCheckInReportDTO;
import com.fangcang.ebk.request.QueryEbkOrderDTO;
import com.fangcang.ebk.request.QueryOrderDetailDTO;
import com.fangcang.ebk.request.RequestIdDTO;
import com.fangcang.ebk.request.UpdateConfirmNoDTO;
import com.fangcang.ebk.request.UpdateConfirmResultDTO;
import com.fangcang.ebk.response.CheckInReportDTO;
import com.fangcang.ebk.response.CheckInReportSummaryDTO;
import com.fangcang.ebk.response.EbkNotifyDTO;
import com.fangcang.ebk.response.EbkOrderDTO;
import com.fangcang.ebk.response.EbkOrderSimpleDTO;
import com.fangcang.ebk.response.EbkOrderSnapDTO;
import com.fangcang.ebk.response.EbkOrderStatisticsDTO;
import com.fangcang.ebk.service.CheckInReportService;
import com.fangcang.ebk.service.EbkOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@RestController
@Slf4j
@RequestMapping(("/ebk/order"))
public class OrderController extends BaseController {

    @Autowired
    private EbkOrderService ebkOrderService;

    @Autowired
    private CheckInReportService checkInReportService;

    @RequestMapping(value = "/orderlist" , method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO orderlist(@RequestBody QueryEbkOrderDTO requestDTO){
        log.info("orderlist param:"+requestDTO);
        ResponseDTO responseDTO=null;
        if(requestDTO.getOrderStatusList()!=null && requestDTO.getOrderStatusList().contains(-1)){
            requestDTO.getOrderStatusList().clear();
            requestDTO.setOrderStatusList(Arrays.asList(1,2,3,4,5));
        }
        try{
            requestDTO.setSupplyCode(super.getCacheUser().getSupplyCode());
            PaginationSupportDTO paginationSupportDTO=ebkOrderService.queryOrderList(requestDTO);
            responseDTO=new ResponseDTO(ResultCodeEnum.SUCCESS.code);
            responseDTO.setModel(paginationSupportDTO);
        }catch (Exception e){
            log.error("ebkOrderService.queryOrderList 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/orderlistform")
    public ResponseDTO orderlistform(QueryEbkOrderDTO requestDTO){
        log.info("orderlist param:"+requestDTO);
        ResponseDTO responseDTO=null;
        if(requestDTO.getOrderStatusList()!=null && requestDTO.getOrderStatusList().contains(-1)){
            requestDTO.getOrderStatusList().clear();
            requestDTO.setOrderStatusList(Arrays.asList(1,2,3,4,5));
        }
        try{
            requestDTO.setSupplyCode(super.getCacheUser().getSupplyCode());
            PaginationSupportDTO paginationSupportDTO=ebkOrderService.queryOrderList(requestDTO);
            responseDTO=new ResponseDTO(ResultCodeEnum.SUCCESS.code);
            responseDTO.setModel(paginationSupportDTO);
        }catch (Exception e){
            log.error("ebkOrderService.queryOrderList 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/orderlistexport")
    public void orderlistexport(QueryEbkOrderDTO requestDTO,HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("orderlistexport param:"+requestDTO);
        requestDTO.setCurrentPage(1);
        requestDTO.setPageSize(999999999);
        requestDTO.setSupplyCode(super.getCacheUser().getSupplyCode());
        PaginationSupportDTO<EbkOrderSimpleDTO> paginationSupportDTO=ebkOrderService.queryOrderList(requestDTO);

        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("EBK订单报表","UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        ExcelUtils.exportExcel(response.getOutputStream(),EbkOrderSimpleDTO.class, paginationSupportDTO.getItemList());
    }

    @RequestMapping(value = "/orderstatistics" , method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO orderstatistics(){
        ResponseDTO responseDTO=null;
        try{
            EbkOrderStatisticsDTO ebkOrderStatisticsDTO=ebkOrderService.queryOrderStatistics(super.getCacheUser().getSupplyCode());
            responseDTO=new ResponseDTO(ResultCodeEnum.SUCCESS.code);
            responseDTO.setModel(ebkOrderStatisticsDTO);
        }catch (Exception e){
            log.error("ebkOrderService.queryOrderStatistics 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/orderdetail" , method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO orderdetail(@RequestBody QueryOrderDetailDTO requestDTO) {
        ResponseDTO responseDTO = null;
        try{
            EbkOrderDTO ebkOrderDTO=ebkOrderService.queryOrderDetail(requestDTO.getSupplyOrderCode());
            if (!StringUtil.isValidString(ebkOrderDTO.getLockUser())
                || super.getCacheUser().getUserName().equals(ebkOrderDTO.getLockUser())){
                ebkOrderDTO.setIsEdit(1);

                LockRequestDTO lockRequestDTO=new LockRequestDTO();
                lockRequestDTO.setLockUser(super.getCacheUser().getUserName());
                lockRequestDTO.setLockName(super.getCacheUser().getRealName());
                lockRequestDTO.setSupplyOrderCodeList(Arrays.asList(requestDTO.getSupplyOrderCode()));
                ebkOrderService.lock(lockRequestDTO);
            }else{
                ebkOrderDTO.setIsEdit(0);
                String locker = ebkOrderDTO.getLockName() +"("+ebkOrderDTO.getLockUser()+")";
                log.info("打开详情失败,订单被{}锁住。",locker);
                return new ResponseDTO(ResultCodeEnum.FAILURE.code,null,"订单已被【"+locker+"】锁定！");
            }
            responseDTO=new ResponseDTO(ResultCodeEnum.SUCCESS.code);
            responseDTO.setModel(ebkOrderDTO);
        }catch (Exception e){
            log.error("ebkOrderService.queryOrderDetail 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/modifyrequestdetail" , method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO modifyrequestdetail(@RequestBody RequestIdDTO requestDTO) {
        ResponseDTO responseDTO = null;
        try{
            EbkOrderSnapDTO ebkOrderSnapDTO=ebkOrderService.queryModifyRequestDetail(requestDTO.getRequestId());
            responseDTO=new ResponseDTO(ResultCodeEnum.SUCCESS.code);
            responseDTO.setModel(ebkOrderSnapDTO);
        }catch (Exception e){
            log.error("ebkOrderService.queryModifyRequestDetail 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/confirm" , method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO confirm(@RequestBody UpdateConfirmResultDTO requestDTO) {
        log.info("confirm param:"+requestDTO);
        ResponseDTO responseDTO = null;
        try{
            requestDTO.setOperator(super.getCacheUser().getUserName());
            requestDTO.setOperatorName(super.getCacheUser().getRealName());
            responseDTO=ebkOrderService.confirmRequest(requestDTO);
        }catch (Exception e){
            log.error("ebkOrderService.confirmRequest 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/modifyconfirmnum" , method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO modifyconfirmnum(@RequestBody UpdateConfirmNoDTO requestDTO) {
        ResponseDTO responseDTO = null;
        try{
            requestDTO.setOperator(super.getCacheUser().getUserName());
            requestDTO.setOperatorName(super.getCacheUser().getRealName());
            responseDTO=ebkOrderService.modifyConfirmNo(requestDTO);
        }catch (Exception e){
            log.error("ebkOrderService.modifyConfirmNo 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/unlock" , method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO unlock(@RequestBody LockRequestDTO requestDTO) {
        ResponseDTO responseDTO = null;
        try{
            requestDTO.setLockUser(super.getCacheUser().getUserName());
            requestDTO.setLockName(super.getCacheUser().getRealName());
            responseDTO=ebkOrderService.unlock(requestDTO);
        }catch (Exception e){
            log.error("ebkOrderService.unlock 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/checkinreport" , method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO checkinreport(@RequestBody QueryCheckInReportDTO requestDTO) {
        log.info("checkinreport param:"+requestDTO);
        ResponseDTO responseDTO = null;
        try{
            requestDTO.setSupplyCode(super.getCacheUser().getSupplyCode());
            CheckInReportSummaryDTO summaryDTO=checkInReportService.queryCheckInReport(requestDTO);
            responseDTO=new ResponseDTO(ResultCodeEnum.SUCCESS.code);
            responseDTO.setModel(summaryDTO);
        }catch (Exception e){
            log.error("checkInReportService.queryCheckInReport 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    /*@RequestMapping(value = "/checkinreportexport1")
    public void checkinreportexport1(QueryCheckInReportDTO requestDTO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("checkinreportexport param:"+requestDTO.toString());
        requestDTO.setCurrentPage(1);
        requestDTO.setPageSize(999999999);
        requestDTO.setSupplyCode(super.getCacheUser().getSupplyCode());
        CheckInReportSummaryDTO summaryDTO=checkInReportService.queryCheckInReport(requestDTO);

        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("在住间夜报表","UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), CheckInReportDTO.class, summaryDTO.getItemList());
        workbook.write(response.getOutputStream());
    }*/

    /*@RequestMapping(value = "/checkinreportexport")
    public View checkinreportexport(QueryCheckInReportDTO requestDTO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("checkinreportexport param:"+requestDTO.toString());
        requestDTO.setCurrentPage(1);
        requestDTO.setPageSize(999999999);
        requestDTO.setSupplyCode(super.getCacheUser().getSupplyCode());
        CheckInReportSummaryDTO summaryDTO=checkInReportService.queryCheckInReport(requestDTO);

        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("在住间夜报表","UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");

        return new AbstractXlsView() {
            @Override
            protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
                ExcelUtils.createSheetByAnnotation(workbook,CheckInReportDTO.class,summaryDTO.getItemList());
            }
        };
    }*/

    @RequestMapping(value = "/checkinreportexport")
    public void checkinreportexport(QueryCheckInReportDTO requestDTO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("checkinreportexport param:"+requestDTO.toString());
        requestDTO.setCurrentPage(1);
        requestDTO.setPageSize(999999999);
        requestDTO.setSupplyCode(super.getCacheUser().getSupplyCode());
        CheckInReportSummaryDTO summaryDTO=checkInReportService.queryCheckInReport(requestDTO);

        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("在住间夜报表","UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");

        ExcelUtils.exportExcel(response.getOutputStream(),CheckInReportDTO.class,summaryDTO.getItemList());
    }

    @RequestMapping(value = "/querynotify" , method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ResponseDTO querynotify() {
        ResponseDTO responseDTO = null;
        try{
            List<EbkNotifyDTO> list=ebkOrderService.queryNotify(super.getCacheUser().getSupplyCode());
            responseDTO=new ResponseDTO(ResultCodeEnum.SUCCESS.code);
            responseDTO.setModel(list);
//            log.info("querynotify,{},{}",super.getCacheUser().getSupplyCode(), JSONObject.toJSONString(list));
        }catch (Exception e){
            log.error("ebkOrderService.queryNotify 异常",e);
            responseDTO=new ResponseDTO(ResultCodeEnum.FAILURE.code,null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }
}
